package com.suneast.suneaststore.modules.personal.order.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.suneast.suneaststore.R;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.bean.personal.order.DetailBean;
import com.suneast.suneaststore.modules.personal.order.OrderHandler;
import com.suneast.suneaststore.modules.personal.order.adapter.GoodsDetailAdapter;
import com.suneast.suneaststore.modules.personal.order.event.DetailResult;
import com.suneast.suneaststore.modules.shopcart.HandlePayFragment;
import com.suneast.suneaststore.ui.fragments.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.noobie.photopicker.util.AnimationUtil;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.BindViews;
import butterknife.OnClick;

public class PurchaseOrderDetail extends BaseFragment implements View.OnClickListener {
    public final static String ORDER_ID = "order_id";
    public final static String ORDER_ST = "order_st";
    private int orderId = -1;
    private int orderStatus = -1;

    @BindView(R.id.title_bar)
    TextView title;
    @BindView(R.id.tv_order_state)
    TextView orderStateTv;
    @BindView(R.id.img_order_state)
    ImageView orderStateImg;
    @BindView(R.id.tv_consignee)
    TextView consigneeTv;
    @BindView(R.id.tv_phone_number)
    TextView phoneNumberTv;
    @BindView(R.id.shipping_address)
    TextView shippingAddress;
    @BindView(R.id.tv_shop_name)
    TextView shopNameTv;
    @BindView(R.id.buyer_requirements)
    TextView tvRequirements;
    @BindView(R.id.tv_payment_content)
    TextView tvPayment;
    @BindView(R.id.tv_invoice_detail)
    TextView tvInvoice;
    @BindView(R.id.tv_order_detail)
    TextView tvOrder;
    @BindView(R.id.rv_goods_detail)
    RecyclerView rvGoods;
    @BindView(R.id.frame_error)
    FrameLayout frError;
    @BindViews({R.id.btn_left, R.id.btn_right})
    Button[] btns;

    private GoodsDetailAdapter adapter;

    private final static String[] invoiceType = {
            "未知", "个人", "企业"
    };

    private final static int[] status_text_ids = new int[]{
            R.string.order_already_canceled,
            R.string.order_wait_pay,
            R.string.order_wait_send,
            R.string.order_wait_receive,
            R.string.order_wait_comment,
            R.string.order_after_sale
    };

    @OnClick(R.id.ib_return_back)
    void onBackPressed() {
        pop();
    }

    @Override
    public int setLayout() {
        return R.layout.fragment_order_detail;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        title.setText(R.string.title_order_detail);
        if (savedInstanceState != null) {
            orderId = savedInstanceState.getInt(ORDER_ID, -1);
            orderStatus = savedInstanceState.getInt(ORDER_ST, -1);
        } else {
            Bundle arguments = getArguments();
            if (arguments != null) {
                orderId = arguments.getInt(ORDER_ID, -1);
                orderStatus = arguments.getInt(ORDER_ST, -1);
            }
        }
        rvGoods.setLayoutManager(new LinearLayoutManager(getContext()));
        adapter = new GoodsDetailAdapter();
        rvGoods.setAdapter(adapter);
        EventBus.getDefault().register(this);
        if (orderStatus != -1) {
            orderStateTv.setText(status_text_ids[orderStatus]);
            Log.e(TAG, "onBindView: orderId = " + orderId);
            OrderHandler.requestOrderDetail(orderId);
        } else {
            // 出错啦
            gotoFailed();
        }
    }

    private void gotoFailed() {
        popError();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(ORDER_ID, orderId);
        outState.putInt(ORDER_ST, orderStatus);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDetailResult(DetailResult result) {
        if (result.getValue() == Flag.Result.SUCCEED) {
            DetailBean bean = result.getBean();
            DetailBean.Address address = bean.getAddress();
            consigneeTv.setText(String.format(getString(R.string.consignee_detail),
                    address.getRealname()));
            phoneNumberTv.setText(address.getMobile());
            shippingAddress.setText(String.format(getString(R.string.shipping_address_detail),
                    address.getAddressInfo()));
            shopNameTv.setText(bean.getMerchname());
            tvRequirements.setText(Html.fromHtml(getString(R.string.buyer_requirements, bean.getRemark())));
            String rmbFormat = getString(R.string.rmb);
            tvPayment.setText(Html.fromHtml(getString(R.string.payment_content,
                    String.format(rmbFormat, bean.getDispatchprice()),
                    String.format(rmbFormat, bean.getDeduction_lb_coin()),
                    String.format(rmbFormat, bean.getDeduction_lb_coin()),
                    String.format(rmbFormat, bean.getPrice()))));
            tvInvoice.setText(getString(R.string.invoice_detail, bean.getExpressname(),
                    invoiceType[bean.getInvoice_type()], bean.getInvoice_no(), bean.getInvoice_info()));
            String payTime = bean.getPaytime();
            tvOrder.setText(getString(R.string.order_info, bean.getOrdersn(), bean.getCreatetime(),
                    TextUtils.isEmpty(payTime) ? "--:--" : payTime));
            adapter.setList(bean.getOrder_goods());
            orderStatus = bean.getStatus();
            switch (orderStatus) {
                case OrderHandler.ORDER_CANCELED:
                    orderStateImg.setImageDrawable(getResources().getDrawable(R.drawable.ic_order_canceled));
                    break;
                case OrderHandler.ORDER_UNPAID:
                    orderStateImg.setImageDrawable(getResources().getDrawable(R.drawable.ic_order_wait_pay));
                    btns[0].setText(getString(R.string.cancel_order));
                    btns[1].setText(getString(R.string.pay_order));
                    btns[0].setVisibility(View.VISIBLE);
                    btns[1].setVisibility(View.VISIBLE);
                    break;
                case OrderHandler.ORDER_TOBE_DELIVERED:
                    orderStateImg.setImageDrawable(getResources().getDrawable(R.drawable.ic_order_wait_send));
                    btns[1].setText(getString(R.string.order_reminder));
                    btns[0].setVisibility(View.INVISIBLE);
                    btns[1].setVisibility(View.VISIBLE);
                    break;
                case OrderHandler.ORDER_TOBE_RECEIVED:
                    orderStateImg.setImageDrawable(getResources().getDrawable(R.drawable.ic_order_wait_receive));
                    btns[1].setText(getString(R.string.receive_confirm));
                    btns[0].setVisibility(View.INVISIBLE);
                    btns[1].setVisibility(View.VISIBLE);
                    break;
                case OrderHandler.ORDER_TOBE_COMMENTED:
                    btns[1].setText(getString(R.string.comment_order));
                    btns[0].setVisibility(View.INVISIBLE);
                    btns[1].setVisibility(View.VISIBLE);
                    break;
                case OrderHandler.ORDER_AFTER_SALES: // 据说这个不会出现，那就先空着
                    break;
            }
        } else {
            // 出错啦
            gotoFailed();
        }
    }

    private void popError() {
        frError.setVisibility(View.VISIBLE);
        new AnimationUtil(getContext(), org.noobie.photopicker.R.anim.translate_up_current)
                .setLinearInterpolator().startAnimation(frError);
    }

    private void hideError() {
        new AnimationUtil(getContext(), org.noobie.photopicker.R.anim.translate_down)
                .setLinearInterpolator().startAnimation(frError);
        frError.setVisibility(View.GONE);
    }

    @OnClick({R.id.btn_left, R.id.btn_right})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_left:
                if (orderStatus == OrderHandler.ORDER_UNPAID) { // 只有未支付有左边的按钮
                    //todo 取消订单
                }
                break;
            case R.id.btn_right:
                switch (orderStatus) {
                    case OrderHandler.ORDER_CANCELED:
                        //todo 取消订单
                        break;
                    case OrderHandler.ORDER_UNPAID:
                        start(new HandlePayFragment().withId(orderId));
                        break;
                    case OrderHandler.ORDER_TOBE_DELIVERED:
                        break;
                    case OrderHandler.ORDER_TOBE_RECEIVED:
                        break;
                    case OrderHandler.ORDER_TOBE_COMMENTED:
                        break;
                    case OrderHandler.ORDER_AFTER_SALES: // 据说这个不会出现，那就先空着
                        break;
                }
                break;
        }
    }
}
